import { defineStore } from 'pinia' //引入pinia
import router from '../router/index'

export const useMenuStore = defineStore("menu", {
  state: () => {
    return ({
      collapse: false,
    })
  },
  getters: {
    getCollapse: (state) => state.collapse
  },
  actions: {
    setCollapse (collapse) {
      this.collapse = collapse
    },
  }
})

export const useKeepAliveStore = defineStore('keepAlivePage', {
  state: () => {
    return ({
      cachePage: [],
      tags: []
    })
  },
  getters: {
  },
  actions: {
    addCachePage (name, title) {
      if (!this.cachePage.includes(name)) {
        this.cachePage.push(name)
        if (title.startsWith('/')) {
          title = title.substring(1)
        }
        this.tags.push({
          name: name,
          title: title
        })
      }
    },
    removePage (name) {
      // 只剩一个页面并且是dashboard的时候不删除
      if (this.tags.length === 1 && this.tags[0].name === 'dashboard') {
        return
      }
      this.cachePage = this.cachePage.filter((item) => item !== name)
      this.tags = this.tags.filter((item) => item.name !== name)
      // 所有页面都删除了 跳转dashboard
      let backPath = '';
      if (this.tags.length === 0) {
        backPath = '/dashboard'
      } else {
        backPath = '/' + this.tags[this.tags.length - 1].name
      }
      router.push(backPath)
    },
    clear () {
      this.cachePage = []
      this.tags = []
      // 所有页面都删除了 跳转dashboard
      router.push('/dashboard')
    }
  }
})